const koa = require('koa'),
    maxrequests = require('koa-maxrequests'),
    middlewares = require('koa-middlewares'),
    cors = require("kcors"),
    mkdirp = require('mkdirp'),
    path = require('path'),
    appModulePath = require('app-module-path');

/*
    require redirect absolute path
 */
appModulePath.addPath(__dirname);

const logger = require('lib/logger'),
    registRouter = require('router'),
    preAnalysis = require('interceptors/preAnalysis'),
    accessLog = require('interceptors/accessLog'),
    notFound = require('interceptors/notFound'),
    error = require('interceptors/error'),
    { dataDir } = require('config');

//创建目录
const tmpDir = path.join(dataDir.root, dataDir.tmp);
mkdirp(tmpDir);

let app = new koa();
app.use(maxrequests());
middlewares.jsonp(app);
app.proxy = true;
app.use(middlewares.bodyParser());
app.use(cors());

//  pre analysis
app.use(preAnalysis)
//  access log
app.use(accessLog)
//  http error handle
app.use(error);

/*
    routes
 */
let router = middlewares.router();
registRouter(router);
app.use(router.routes());
app.use(router.allowedMethods());

app.use(notFound);

/*
    system Error handler
 */
app.on('error', (err, ctx) => {
    console.log('system error', err);
    err.url = err.url || ctx.request.url;
    logger.error(err);
});

module.exports = app;